<template>
  <div class="course-list">
    <div class="search-bar">
      <input
        v-model="searchQuery"
        type="text"
        placeholder="搜索课程..."
        @input="handleSearch"
      >
      <div class="filters">
        <select v-model="selectedCategory">
          <option value="">全部分类</option>
          <option v-for="category in categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
        <select v-model="sortBy">
          <option value="latest">最新</option>
          <option value="popular">最热</option>
          <option value="rating">评分</option>
        </select>
      </div>
    </div>

    <div class="course-grid">
      <div v-for="course in filteredCourses" :key="course.id" class="course-card">
        <img :src="course.coverImage" :alt="course.title">
        <div class="course-info">
          <h3>{{ course.title }}</h3>
          <p class="description">{{ course.description }}</p>
          <div class="meta">
            <span class="teacher">{{ course.teacher }}</span>
            <span class="students">{{ course.studentCount }}人学习</span>
            <span class="rating">
              <i class="fas fa-star"></i>
              {{ course.rating }}
            </span>
          </div>
          <div class="price-action">
            <span class="price">¥{{ course.price }}</span>
            <button @click="enrollCourse(course.id)">立即报名</button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <i class="fas fa-spinner fa-spin"></i>
      加载中...
    </div>

    <div v-if="!loading && filteredCourses.length === 0" class="empty-state">
      暂无相关课程
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useCourseStore } from '../../stores/course.store'
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'

const courseStore = useCourseStore()
const router = useRouter()

const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('latest')
const loading = ref(false)

const categories = computed(() => courseStore.categories)
const courses = computed(() => courseStore.courses)

const filteredCourses = computed(() => {
  let result = [...courses.value]

  if (searchQuery.value) {
    result = result.filter(course =>
      course.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      course.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  if (selectedCategory.value) {
    result = result.filter(course => course.categoryId === selectedCategory.value)
  }

  switch (sortBy.value) {
    case 'popular':
      result.sort((a, b) => b.studentCount - a.studentCount)
      break
    case 'rating':
      result.sort((a, b) => b.rating - a.rating)
      break
    default:
      result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
  }

  return result
})

const handleSearch = debounce(() => {
  courseStore.searchCourses(searchQuery.value)
}, 300)

const enrollCourse = async (courseId: string) => {
  try {
    await courseStore.enrollCourse(courseId)
    router.push(`/courses/${courseId}`)
  } catch (error) {
    console.error('报名课程失败:', error)
  }
}

onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      courseStore.fetchCategories(),
      courseStore.fetchCourses()
    ])
  } catch (error) {
    console.error('加载课程数据失败:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped lang="scss">
.course-list {
  .search-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;

    input {
      flex: 1;
      padding: 8px 16px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      font-size: 14px;

      &:focus {
        outline: none;
        border-color: #1890ff;
      }
    }

    .filters {
      display: flex;
      gap: 8px;

      select {
        padding: 8px 16px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background-color: white;
        font-size: 14px;
        cursor: pointer;

        &:focus {
          outline: none;
          border-color: #1890ff;
        }
      }
    }
  }

  .course-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 24px;

    .course-card {
      background: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      transition: transform 0.3s;

      &:hover {
        transform: translateY(-4px);
      }

      img {
        width: 100%;
        height: 160px;
        object-fit: cover;
      }

      .course-info {
        padding: 16px;

        h3 {
          margin: 0 0 8px;
          font-size: 16px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .description {
          margin: 0 0 12px;
          font-size: 14px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          height: 40px;
        }

        .meta {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 12px;
          font-size: 12px;
          color: #999;

          .rating {
            color: #faad14;
          }
        }

        .price-action {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .price {
            font-size: 18px;
            color: #f5222d;
            font-weight: bold;
          }

          button {
            padding: 6px 16px;
            border: none;
            border-radius: 4px;
            background-color: #1890ff;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
              background-color: #40a9ff;
            }
          }
        }
      }
    }
  }

  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 32px;
    color: #666;

    i {
      font-size: 20px;
      color: #1890ff;
    }
  }

  .empty-state {
    text-align: center;
    padding: 32px;
    color: #999;
  }
}
</style>